﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 库位信息
    /// </summary>
    [ApiDescriptionSettings("基础信息", Name = "WmsPlace", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsPlaceService : IWmsPlaceService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsPlace, MasterDbContextLocator> _wmsPlaceRep;
        private readonly IRepository<WmsArea> _wmsAreaRep;


        public WmsPlaceService(
            IRepository<WmsArea> wmsAreaRep,
            IRepository<WmsPlace, MasterDbContextLocator> wmsPlaceRep
        )
        {
            _wmsAreaRep = wmsAreaRep;
            _wmsPlaceRep = wmsPlaceRep;
        }

        /// <summary>
        /// 分页查询库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsPlaceOutput>> Page([FromQuery] WmsPlaceSearch input)
        {
            var wmsPlaces = await _wmsPlaceRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.Placecode), u => EF.Functions.Like(u.PlaceCode, $"%{input.Placecode.Trim()}%"))
                                     .Where(input.Placestatus != null, u => u.PlaceStatus == input.Placestatus)
                                     .Where(input.Areaid > 0, u => u.AreaId == input.Areaid)
                                     .Where(input.Rowno != null, u => u.RowNo == input.Rowno)
                                     .Where(input.Columnno != null, u => u.ColumnNo == input.Columnno)
                                     .Where(input.Layerno != null, u => u.LayerNo == input.Layerno)
                                     .Where(input.Aisle != null, u => u.Aisle == input.Aisle)
                                     .Where(input.Islock != null, u => u.Islock == input.Islock)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsPlaceSearch>(input))
                                     .ProjectToType<WmsPlaceOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsPlaces;
        }

        /// <summary>
        /// 增加库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsPlaceInput input)
        {
            var wmsPlace = input.Adapt<WmsPlace>();
            for (int t = 1; t <= wmsPlace.RowNo; t++)   //循环排
            {
                for (int i = 1; i <= wmsPlace.ColumnNo; i++)   //循环列
                {
                    for (int j = 1; j <= wmsPlace.LayerNo; j++)  //循环层
                    {
                        for (int f = 1; f <= wmsPlace.DeepcellNo; f++)   //循环进深号
                        {
                            var model = new WmsPlace();
                            model.PlaceStatus = Core.Enum.PlaceStatus.KONGXIAN;
                            model.AreaId = wmsPlace.AreaId;
                            model.RowNo = t;
                            model.ColumnNo = i;
                            model.LayerNo = j;
                            model.DeepcellNo = f;
                            model.Aisle = wmsPlace.Aisle;
                            model.Islock = YesOrNot.N;
                            model.Length = new decimal(1.2);
                            model.Width = new decimal(1.5);
                            model.Height = new decimal(1.8);
                            model.MaxWeight = new decimal(2.8);
                            model.HeightLevel = Core.Enum.Heightlevel.DI;
                            model.Priority = 0;
                            model.PlaceCode = String.Format("{0}-{1}-{2}-{3}-{4}", wmsPlace.Aisle,t, i, j, f);
                            var isExit = await _wmsPlaceRep.AnyAsync(n => n.PlaceCode == model.PlaceCode);
                            if(!isExit) await _wmsPlaceRep.InsertAsync(model);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 删除库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsPlaceInput input)
        {
            var wmsPlace = await _wmsPlaceRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsPlaceRep.DeleteAsync(wmsPlace);
        }

        /// <summary>
        /// 更新库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsPlaceInput input)
        {
            var isExist = await _wmsPlaceRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsPlace = input.Adapt<WmsPlace>();
            await _wmsPlaceRep.UpdateAsync(wmsPlace, ignoreNullValues: true);
        }

        /// <summary>
        /// 获取库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsPlaceOutput> Get([FromQuery] QueryeWmsPlaceInput input)
        {
            return (await _wmsPlaceRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsPlaceOutput>();
        }

        /// <summary>
        /// 获取库位信息列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsPlaceOutput>> List([FromQuery] WmsPlaceInput input)
        {
            return await _wmsPlaceRep.DetachedEntities.ProjectToType<WmsPlaceOutput>().ToListAsync();
        }

        /// <summary>
        /// 获取WmsArea列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("fkWmsArea")]
        public async Task<dynamic> FkWmsAreaList()
        {
            var list = await _wmsAreaRep.DetachedEntities.ToListAsync();
            return list.Select(e => new { Code = e.Id, Name = e.AreaName });
        }

    }
}
